<template>
  <div class="app-container">
    <el-row :gutter="20">

      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>区域代理列表</span>
          </div>
          <div class="head-container">
            <el-tree
              :data="proxyOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              default-expand-all
              @node-click="handleNodeClick"
            />
          </div>
        </el-card>
       
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-card class="box-card">
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="用户名称" prop="nickName">
              <el-input
                v-model="queryParams.nickName"
                placeholder="请输入用户名称"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="用户状态"
                clearable
                size="small"
                style="width: 240px"
              >
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

         

          <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <!-- <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" /> -->
            <!-- <el-table-column label="用户头像" align="center" key="avatar" prop="avatar" >
              <template slot-scope="scope">
                <el-image  v-if="scope.row.avatar"
                  style="width: 50px; height: 50px;border-radius: 50%;"
                  :src="scope.row.avatar" 
                  >
                </el-image>
              </template>
            </el-table-column> -->
            <el-table-column label="账号" align="center" key="userName" prop="userName"  :show-overflow-tooltip="true" >
              <template slot-scope="scope">
                <el-button
                    type="text"
                    @click="handleShow(scope.row)"
                  >{{scope.row.userName}}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName"  :show-overflow-tooltip="true" />
            <el-table-column label="用户名称" align="center" key="realName" prop="realName"  :show-overflow-tooltip="true" />
            <el-table-column label="用户性别" align="center" prop="sex" :formatter="sexFormat" />
            <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber"  width="120" />
            <el-table-column label="公司名称" align="center" prop="company.name"   width="150" />
            <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="150">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="积分" align="center" prop="integral"  />
            <el-table-column label="余额" align="center" prop="amount"  />
            <el-table-column label="收入" align="center" prop="inFee"  />
            <el-table-column label="支出" align="center" prop="outFee"  />
            <el-table-column
              label="操作"
              align="center"
              width="170"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-house" 
                  @click="handleCompany(scope.row)"
                >公司</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-tickets" 
                  @click="handleOrderList(scope.row)"
                >接单记录</el-button>
                <!-- <el-button
                  v-if="scope.row.userId !== 1"
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:user:remove']"
                >删除</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-key"
                  @click="handleResetPwd(scope.row)"
                  v-hasPermi="['system:user:resetPwd']"
                >重置</el-button> -->
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
        
      </el-col>
    </el-row>


    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form"  label-width="120px" disabled>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
            </el-form-item>
          </el-col>
       
          <el-col :span="12">
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input v-model="form.phonenumber" placeholder="请输入手机号码"  />
              </el-form-item>
          </el-col>
        </el-row>
       
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option
                  v-for="dict in sexOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idcard">
              <el-input v-model="form.idcard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="form.realName" placeholder="真实姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证正面" prop="cardZheng">
              <imageUpload v-model="form.cardZheng"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证反面" prop="cardFan">
              <imageUpload v-model="form.cardFan"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>          
          <el-col :span="24">
            <el-form-item label="服务范围">
              <el-input v-model="form.tagshow" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改公司管理对话框 -->
    <el-dialog :title="title" :visible.sync="companyOpen" width="50%"  append-to-body >
      <el-form ref="form" :model="form"  label-width="120px" :disabled="true">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入公司名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="信用代码" prop="xyCode">
              <el-input v-model="form.xyCode" placeholder="请输入信用代码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="法人代表" prop="frName">
              <el-input v-model="form.frName" placeholder="请输入法人代表名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="frPhone">
              <el-input v-model="form.frPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="法人身份证号" prop="idcard">
              <el-input v-model="form.idcard" placeholder="请输入法人身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="营业执照照片" prop="cardZheng">
              <imageUpload v-model="form.cardZheng"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户许可证明" prop="cardFan">
              <imageUpload v-model="form.cardFan"/>
            </el-form-item>
          </el-col>
        </el-row>
      
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="公司地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入公司地址" />
          </el-form-item>
          </el-col>
        </el-row>
        
      
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
   
   <!-- 订单管理对话框 -->
    <el-dialog title="订单管理" :visible.sync="orderShow" width="50%" append-to-body>
      <el-table v-loading="orderloading" :data="orderList" show-summ="false">
          <el-table-column label="订单编号" align="center" prop="num" width="170" >
          </el-table-column>
          <el-table-column label="订单信息" align="center" prop="attribute" />
          <el-table-column label="预约时间" align="center" prop="orderTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.orderTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="联系人" align="center" prop="username" />
          <el-table-column label="联系电话" align="center" prop="telephone" />
          <!-- <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"  /> -->
          <el-table-column label="备注" align="center" prop="remark" />
          <!-- <el-table-column label="应付" align="center" prop="payable" /> -->
          <el-table-column label="实付" align="center" prop="pay" />
        </el-table>
        
        <pagination
          v-show="orderTotal>0"
          :total="orderTotal"
          :page.sync="queryOrderParams.pageNum"
          :limit.sync="queryOrderParams.pageSize"
          @pagination="getOrderList"
        />
        <div slot="footer" class="dialog-footer" style="text-align:center;">
          <el-button @click="cancel">返 回</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCompanyUser, getUser, delUser } from "@/api/system/user";
import { getCompany } from "@/api/business/company";
import { getToken } from "@/utils/auth";
import { treeListProxy } from "@/api/business/proxy";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listOrder } from "@/api/business/order";
import ImageUpload from '@/components/ImageUpload';

export default {
  name: "User",
  components: { Treeselect, ImageUpload },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      orderloading: true,
      orderShow: false,
      companyOpen: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      orderTotal: 0,
      // 用户表格数据
      userList: null,
      orderList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      proxyOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {
        proxy: {}
      },
      currentProxy: null,
      defaultProps: {
        children: "children",
        label: "name"
      },
      user: null,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        proxyId: undefined
      },
      // 查询参数
      queryOrderParams: {
        pageNum: 1,
        pageSize: 10,
        num: null,
        detail: null,
        orderTime: null,
        userId: null,
        username: null,
        telephone: null,
        receiveId: null,
        receiveName: null,
        receivePhone: null,
        receiveLimit: null,
        group: null,
        attribute: null,
        status: null,
        createName: null,
        createId: null,
        createTime: null,
        payable: null,
        pay: null,
        payMethod: null
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
      
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_user_sex").then(response => {
      this.sexOptions = response.data;
    });
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      this.queryParams.proxyId = this.currentProxy?this.currentProxy.id : null;
      listCompanyUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeListProxy().then(response => {
        this.proxyOptions = response.data;
      });
    },
    // 用户性别字典翻译
    sexFormat(row, column) {
      return this.selectDictLabel(this.sexOptions, row.sex);
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.proxyId = data.id;
      this.currentProxy = data;
      this.getList();
    },
   
    // 取消按钮
    cancel() {
      this.open = false;
      this.orderShow = false;
      this.companyOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        proxyId: null,
        proxy: {},
        company: {},
        companyId: null,
        postIds: [],
        roleIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
   /** 修改按钮操作 */
    handleShow(row) {
      this.reset();
      this.disabled = true;
      const userId = row.userId || this.ids;
      getUser(userId).then(response => {
        this.form = response.data;
        if (this.form.tags) {
          this.form.tagshow = this.form.tags.split(";").map(a=>a.split("=")[1]).filter(a=>a).join();
        }
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.form.postIds = response.postIds;
        this.form.roleIds = response.roleIds;
        this.open = true;
        this.title = "查看用户";
        this.form.password = "";
      });
    },
   /** 新增按钮操作 */
    handleAdd() {
      if (!this.currentProxy) {
        this.msgError("请先选择区域代理再添加用户.");
        return;
      }
      this.reset();
      getUser().then(response => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.open = true;
        this.title = "添加用户";
        this.form.password = this.initPassword;
        this.form.proxyId = this.currentProxy.id;
        this.form.proxy.name = this.currentProxy.name;
      });
    },
  
    handleCompany(row){
      getCompany(row.companyId).then(response => {
        this.form = response.data;
        this.disabled = true;
        this.companyOpen = true;
        this.title = "查看公司信息";

      });
    },
    /** 查询订单管理列表 */
    getOrderList() {
      this.orderloading = true;
      this.queryOrderParams.receiveId = this.user.userId;
      this.queryOrderParams.params = {};
      if (null != this.daterangeOrderTime && '' != this.daterangeOrderTime) {
        this.queryOrderParams.params["beginOrderTime"] = this.daterangeOrderTime[0];
        this.queryOrderParams.params["endOrderTime"] = this.daterangeOrderTime[1];
      }
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryOrderParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryOrderParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listOrder(this.queryOrderParams).then(response => {
        this.orderList = response.rows;
        this.orderTotal = response.total;
        this.orderloading = false;
      });
    },
    handleOrderList(row){
      this.orderShow = true;
      this.user = row;
      this.getOrderList();
   }
  }
};
</script>